package top.pmwly.service.Impl;
import java.util.Date;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import top.pmwly.common.domain.UserSecurity;
import top.pmwly.common.domain.vo.MyinfoVo;
import top.pmwly.common.execption.BaseException;
import top.pmwly.common.jwt.JwtToken;
import top.pmwly.common.param.UserLoginParam;
import top.pmwly.common.constant.ReslutEnum;
import top.pmwly.common.reslut.ReslutBean;
import top.pmwly.dao.mapper.SysUserMapper;
import top.pmwly.dao.pojo.SysRole;
import top.pmwly.dao.pojo.SysUser;
import top.pmwly.service.ISysRoleService;
import top.pmwly.service.ISysUserService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 * @author Herther
 * @since 2021-09-21
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private UserDetailsService userDetailsService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private JwtToken jwtToken;

    @Value("${jwt.tokenHead}")
    private String header;

    /**
     * 登录返回token
     * @param userLoginParam
     * @return
     */
    @Override
    public ReslutBean login(UserLoginParam userLoginParam) {
        //登录
        UserDetails userDetails =
                userDetailsService.loadUserByUsername(userLoginParam.getUserName());
        //判断用户是否不存在，判断密码是否一致
        if (null == userDetails || !passwordEncoder.matches(
                userLoginParam.getPassword() , userDetails.getPassword())){
            return ReslutBean.FAIL(ReslutEnum.FAIL_LOGIN);
        }
        //账号是否被禁用
        if (!userDetails.isEnabled()){
            return ReslutBean.FAIL(ReslutEnum.FAIL_ENABLED);
        }
        //更新Security登录用户
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //放入到全局对象当中去
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtToken.generateToken(userDetails);
        //返回前端数据
        Map<String, Object> data = new HashMap<String,Object>();
        data.put("token", token);
        data.put("tokenHead", header);
        //返回
        return ReslutBean.SUCCESS(ReslutEnum.SUCCESS_LOGIN,data);
    }

    /**
     * 根据用户名获取用户信息
     * @param name 用户名
     * @return
     */
    @Override
    public UserSecurity getInfo(String name) {
        //构建查询条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        //用户名
        wrapper.eq("user_name", name);
        ////状态是正常的
        //wrapper.eq("status", 0);
        //执行查询
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (null == sysUser){
            return null;
        }
        UserSecurity userSecurity = new UserSecurity(sysUser);
        return userSecurity;
    }

    /**
     * 获取个人信息
     * @param userName
     * @return
     */
    @Override
    public ReslutBean getMyinfoVo(String userName) {
        //构建查询条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        //用户名
        wrapper.eq("user_name", userName);
        //执行查询
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (null == sysUser){
            throw new BaseException(ReslutEnum.FAIL_USER_NOT_ENABLED);
        }
        //查询用户角色
        SysRole role = sysRoleService.getRole(sysUser.getUserId());
        //封装返回对象
        MyinfoVo myinfoVo = new MyinfoVo();
        BeanUtil.copyProperties(sysUser, myinfoVo);
        //BeanUtils.copyProperties(myinfoVo, sysUser);
        //复制对象
        myinfoVo.setEnabled(role.getStatus());
        myinfoVo.setRoleName(role.getRoleName());
        myinfoVo.setRoleKey(role.getRoleKey());


        //放入角色名称
        myinfoVo.setRoleName(role.getRoleName());
        //返回
        return ReslutBean.SUCCESS(ReslutEnum.SUCCESS,myinfoVo);
    }

}
